﻿using System;

namespace ComToolkit.Data
{
    public class AdoParameter : IDisposable
    {
        internal dynamic adoParameter;

        internal AdoParameter(dynamic adoParameter, string name = "", object value = null)
        {
            this.adoParameter = adoParameter;
            Name = name;
            Value = value;
            Type = ResolveDbType(value);
            Size = GetSize(value, Type);
            Direction = ParameterDirection.Input;
        }

        public string Name
        {
            get { return adoParameter.Name; }
            set { adoParameter.Name = value; }
        }

        public object Value
        {
            get { return adoParameter.Value; }
            set { adoParameter.Value = value; }
        }

        public DbType Type
        {
            get { return (DbType)adoParameter.Type; }
            set { adoParameter.Type = (int)value; }
        }

        public ParameterDirection Direction
        {
            get { return (ParameterDirection)adoParameter.Direction; }
            set { adoParameter.Direction = (int)value; }
        }

        public int Size
        {
            get { return (int)adoParameter.Size; }
            set { adoParameter.Size = (int)value; }
        }

        private DbType ResolveDbType(object value)
        {
            if (value is string)
                return DbType.String;
            if (value is Guid)
                return DbType.Guid;
            if (value is int || value is double || value is float || value is double)
                return DbType.Numeric;
            return DbType.Unknown;
        }

        private int GetSize(object value, DbType type)
        {
            if (type == DbType.Guid)
                return 32;
            if (type == DbType.String)
                return value.ToString().Length;
            return 0;
        }

        public void Dispose()
        {
            adoParameter = null;
        }
    }

    //http://www.w3schools.com/ado/prop_prop_type.asp
    //TODO: Test rest available types.
    public enum DbType
    {
        Unknown = 0,
        Guid = 72,
        Numeric = 139,
        String = 200
    }

    //TODO: Test all types
    public enum ParameterDirection
    {
        Unknown = 0,
        Input = 1,
        InputOutput = 2,
        ParamOutput = 3,
        ReturnValue = 4
    }
}
